package com.winz.cultureapp.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.mine.xrecyclerview.XRecyclerView;
import com.mine.xrecyclerview.rcvadapter.OnItemClickListener;
import com.winz.cultureapp.R;
import com.winz.cultureapp.adapter.xrcv.CommunityDataAdapter;
import com.winz.cultureapp.base.BaseAppCompatActivity;
import com.winz.cultureapp.constants.Constants;
import com.winz.cultureapp.entity.CommunityListBean;
import com.winz.cultureapp.filter.activity.LocationPopupWindow;
import com.winz.cultureapp.filter.activity.PxPopupWindow;
import com.winz.cultureapp.filter.community.TypePopupWindow;
import com.winz.cultureapp.http.OnResponeListener;
import com.winz.cultureapp.http.request.RequestFactory;
import com.winz.cultureapp.http.util.HttpUitls;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;
import com.winz.filterbar.FilterBar;
import com.winz.filterbar.FilterTab;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 文体社团
 */
public class CommunityActivity extends BaseAppCompatActivity implements OnItemClickListener, XRecyclerView.LoadingListener, FilterBar.SelectedMenuListener {
    @BindView(R.id.tv_top_title)
    public TextView mTv_top_title;

    @BindView(R.id.xrcv_community)
    public XRecyclerView mXrcv_community;
    @BindView(R.id.fb_activity)
    FilterBar mFb_community;

    private boolean isRefresh = true;
    private int limit = 10;
    private int page = 1;
    private int totalPage = 0;
    private List<CommunityListBean.DataBean.ListBean> mDatas;
    private CommunityDataAdapter mAdapter;

    private LocationPopupWindow mPop_location;
    private TypePopupWindow mPop_type;
    private PxPopupWindow mPop_Px;
    private Map<FilterTab, PopupWindow> map_pop = new HashMap<>();

    private String leagueCategoryId = "0";
    private String areaId = "0";
    private String sort = "0";


    @Override
    protected int contentView() {
        return R.layout.activity_community;
    }

    @Override
    protected void initViews() {

        mTv_top_title.setText(R.string.community_top_title);
        mDatas = new ArrayList<>();


        // XrecyclerView
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mXrcv_community.setLayoutManager(manager);
        mXrcv_community.setPullRefreshEnabled(true);
        mXrcv_community.setLoadingMoreEnabled(true);

        mXrcv_community.setFocusable(false);
        mXrcv_community.setFocusableInTouchMode(false);

        mAdapter = new CommunityDataAdapter(this, mDatas, R.layout.empty_view, R.layout.item_community_list);
//        // 添加头部
//        View header = LayoutInflater.from(this).inflate(R.layout.view_header_community, null);
//        mXrcv_community.addHeaderView(header);
//        // 初始化头部信息
//        initHeaerView(header);


        // 初始化
        mPop_location = new LocationPopupWindow(this,mFb_community.getTabs().get(0));
        map_pop.put(mFb_community.getTabs().get(0),mPop_location);
        mPop_type = new TypePopupWindow(this, mFb_community.getTabs().get(1));
        map_pop.put(mFb_community.getTabs().get(1), mPop_type);
        mPop_Px = new PxPopupWindow(this, mFb_community.getTabs().get(2));
        map_pop.put(mFb_community.getTabs().get(2), mPop_Px);

    }

//    private void initHeaerView(View header) {
//        header.findViewById(R.id.rl_header_item1).setOnClickListener(this);
//        header.findViewById(R.id.rl_header_item2).setOnClickListener(this);
//
//
//    }

    @Override
    protected void initEvents() {
        mXrcv_community.setAdapter(mAdapter);
        mXrcv_community.setLoadingListener(this);
        mAdapter.setOnItemClickListener(this);

        mFb_community.setSelectedMenuListener(this);

        /* 区域 */
        mPop_location.setOnFinishListener(new LocationPopupWindow.OnFinishListener() {
            @Override
            public void onFinish(FilterTab flag, String data) {
                flag.setText(data.split(",")[0]);
                map_pop.get(flag).dismiss();
                if (data.split(",").length>1){
                    areaId = data.split(",")[1];
                    getList();
                }
            }
        });
        mPop_location.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPop_location.getFlag().setFilterTabSelected(false,FilterTab.FLAG_OTHER);
            }
        });

        /* 分类 */
        mPop_type.setOnFinishListener(new TypePopupWindow.OnFinishListener() {
            @Override
            public void onFinish(FilterTab flag, String data) {
                flag.setText(data.split(",")[0]);
                map_pop.get(flag).dismiss();
                if (data.split(",").length>1){
                    leagueCategoryId = data.split(",")[1];
                    getList();
                }
            }
        });
        mPop_type.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPop_type.getFlag().setFilterTabSelected(false,FilterTab.FLAG_OTHER);
            }
        });

        /* 排序 */
        mPop_Px.setOnFinishListener(new PxPopupWindow.OnFinishListener() {
            @Override
            public void onFinish(FilterTab flag, String data) {
                flag.setText(data.split(",")[0]);
                map_pop.get(flag).dismiss();
                if (data.split(",").length>1){
                    sort = data.split(",")[1];
                    getList();
                }
            }
        });
        mPop_Px.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                mFb_activity.getTabSelectedObervable();
                mPop_Px.getFlag().setFilterTabSelected(false,FilterTab.FLAG_OTHER);
            }
        });
    }

    @Override
    protected void loadDatas(Intent intent) {
        getList();
    }

    /**
     * 获取数据列表
     */
    private void getList() {
        showProgressDialog();

        HttpUitls.onGet("league", RequestFactory.getInstance().league(page + "",limit + "",leagueCategoryId,areaId,sort),new OnResponeListener<CommunityListBean>() {
            @Override
            public void onSuccess(CommunityListBean communityListBean) {
                Logger.d("league==>>", JsonUtil.getJsonFromObj(communityListBean));
                if (communityListBean.code == 0) {
                            totalPage = communityListBean.totalPage;
                    if (communityListBean.data.list != null && communityListBean.data.list.size() > 0) {
                        mXrcv_community.setLoadingMoreEnabled(true);
                        if (isRefresh) {
                            mDatas.clear();
                            mDatas = communityListBean.data.list;
                        } else {
                            mDatas.addAll(communityListBean.data.list);
                        }
                    } else {
                        mDatas.clear();
                        CommunityListBean.DataBean.ListBean empty = new CommunityListBean.DataBean.ListBean();
                        empty.layout_type = -1;
                        mDatas.add(empty);
                        mXrcv_community.setLoadingMoreEnabled(false);
                    }
                    mAdapter.setDatas(mDatas);
                } else {
                    showMsg(communityListBean.msg);
                }
                if (isRefresh) {
                    mXrcv_community.refreshComplete();
                } else {
                    mXrcv_community.loadMoreComplete();
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                Logger.d("league==>>", error);
                if (isRefresh) {
                    mXrcv_community.refreshComplete();
                } else {
                    mXrcv_community.loadMoreComplete();
                }
            }
        });

    }

    @OnClick({R.id.fl_back,R.id.rl_right})
    public void knife(View view) {
        switch (view.getId()) {
            case R.id.fl_back:
                finish();
                break;
            case R.id.rl_right:

                startActivity(MyCommunityActivity.class,false);
                break;
        }
    }



    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        isRefresh = true;
        page = 1;
        loadDatas(null);
    }

    /**
     * 加载
     */
    @Override
    public void onLoadMore() {
        isRefresh = false;
        if (page >= totalPage) {
            mXrcv_community.setNoMore(true, true, "没有更多数据了");
        } else {
            page++;
            loadDatas(null);
        }
    }

    /**
     * item点击事件
     *
     * @param parent
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(ViewGroup parent, View view, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.KEY.COMMUNITY.ITEM_ID,mDatas.get(position).leagueId);
        bundle.putString(Constants.KEY.COMMUNITY.ITEM_DES_HREF,Constants.URL.IP + "/league/detail/" + mDatas.get(position).leagueId);

        startActivity(CommunityDesActivity.class,false,bundle);
    }

    @Override
    public boolean onItemLongClick(ViewGroup parent, View view, int position) {
        return false;
    }


    /**
     * 选择筛选项
     */
    @Override
    public void onSelectedMenu(FilterTab view, boolean selected) {
        // 打开或者关闭筛选弹窗
        if (selected){
            map_pop.get(view).showAsDropDown(view);
        }else {
            map_pop.get(view).dismiss();
        }

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
